﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using MyChannel.Library;
using MyChannel.DetailCategory;
using MyChannel.Resources;
using Newtonsoft.Json;
using MyChannel.DownloadComponent;
using Coding4Fun.Toolkit.Controls;

namespace MyChannel
{
    public partial class CategoryDetailPage : PhoneApplicationPage
    {
        MD5 md5 = new MD5();
        bool isload = false;
        string _title = "";
        public CategoryDetailPage()
        {
            InitializeComponent();
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            NavigationContext.QueryString.TryGetValue("name", out _title);
            title.Text = _title;
            List_Home.SelectedIndex = -1;
            LoadData();
            base.OnNavigatedTo(e);
        }
        private void LoadData()
        {
            if (!isload)
            {
                ProgressCategoryDetail.Visibility = System.Windows.Visibility.Visible;
                int page = 0;
                int size = 10;
                WebClient webclient = new WebClient();
                webclient.DownloadStringCompleted += webclient_DownloadStringCompleted;
                string timetamp = md5.GetTime();
                webclient.DownloadStringAsync(new Uri(AppResources.Server + string.Format(AppResources.GetDetailCategory, App.CategoryAction, page.ToString(), size.ToString(), App.OsName, App.OsVersion, App.DeviceID, md5.GetMD5(AppResources.MD5KEY + timetamp), timetamp, App.DeviceName)));
            }

        }
        void webclient_DownloadStringCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e)
        {
            try
            {
                 string json = e.Result;
                if (!string.IsNullOrEmpty(json))
                {
                    RootDetailCategoryObject rootDetailCategoryObject = JsonConvert.DeserializeObject<RootDetailCategoryObject>(json);
                    List_Home.DataContext = rootDetailCategoryObject.Data;
                    isload = true;
                    ProgressCategoryDetail.Visibility = System.Windows.Visibility.Collapsed;
                    network_error.Visibility = System.Windows.Visibility.Collapsed;
                }
            }
            catch
            {
                ProgressCategoryDetail.Visibility = System.Windows.Visibility.Collapsed;
                network_error.Visibility = System.Windows.Visibility.Visible;
            }
        }
        private void Reload_Click(object sender, RoutedEventArgs e)
        {
            network_error.Visibility = System.Windows.Visibility.Collapsed;
            isload = false;
            LoadData();
        }
        private void List_Home_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (List_Home.SelectedIndex < 0)
                return;
            App.URL = (List_Home.SelectedItem as DetailCategoryObject).Link;
            int type = int.Parse((List_Home.SelectedItem as DetailCategoryObject).Type);
            switch (type)
            {
                case 0:
                    {
                        NavigationService.Navigate(new Uri("/ViewVideoPage.xaml?type=0", UriKind.Relative));
                    } break;
                case 1:
                    {

                    } break;
                default: break;
            }

        }

        DetailCategoryObject _DetailObject;
        private void Cate_Item_Hold(object sender, System.Windows.Input.GestureEventArgs e)
        {
            _DetailObject = (sender as Grid).DataContext as DetailCategoryObject;

            Grid item = sender as Grid;

            ContextMenu contextMenu = new ContextMenu();

            MenuItem addVideoFavorite = new MenuItem();
            addVideoFavorite.Header = "Add to favorite";
            addVideoFavorite.Click += addVideoFavorite_Click;

            MenuItem download = new MenuItem();
            download.Header = "Download";
            download.Click += download_Click;

            contextMenu.Items.Add(addVideoFavorite);
            contextMenu.Items.Add(download);
            ContextMenuService.SetContextMenu(item, contextMenu);
            contextMenu.IsOpen = true;
        }

        void download_Click(object sender, RoutedEventArgs e)
        {
            WebClient client = new WebClient();
            client.OpenReadCompleted += (s, ee) =>
            {
                App.PicToIsoStore(ee.Result, _DetailObject.Name + ".jpg");
            };
            client.OpenReadAsync(new Uri(_DetailObject.Image, UriKind.Absolute));

            LocalVideo localvideo = new LocalVideo
            {
                Id = _DetailObject.Name,
                Name = _DetailObject.Name,
                Img = _DetailObject.Name + ".jpg",
                Url = _DetailObject.Link,
                Playlist = App.ViewModel.PlaylistList[0],
                Key = _DetailObject.Name
            };

            App.ViewModel.AddVideo(localvideo);
            DownloadingPage.Download(localvideo);
            var toast = GetToastWithImgAndTitle(localvideo.Name + " has starting download", "");
            toast.TextWrapping = TextWrapping.Wrap;
            toast.Show();
        }

        void addVideoFavorite_Click(object sender, RoutedEventArgs e)
        {
          
        }

        private static ToastPrompt GetToastWithImgAndTitle(string _title, string _content)
        {
            return new ToastPrompt
            {
                Title = _title,
                TextOrientation = System.Windows.Controls.Orientation.Vertical,
                Message = _content
            };
        }

    }
}